var API = require('API').[[MODEL_NAME]];
var GRID = require('[[MODEL_NAME]].aggrid');

module.exports = ['$scope','$rootScope','$location','$routeParams','$timeout',
    function($scope, $rootScope, $location, $routeParams, $timeout){

        $scope.add_open = false;
        $scope.edit_open = false;
        $scope.grid = GRID.grid;

        $scope.record_add = {};
        $scope.record_edit = {};

        $scope.submit_add = function(){
            //
            API.add($scope.record_add, function(){
                $scope.$apply(function(){
                    $scope.refresh();
                });
            }, function(e){alert(e);});
        };

        $scope.open_edit = function (data) {
            $scope.edit_open = true;
            $scope.record_edit = data;
        };

        GRID.on('open', function (row) {
            $scope.$apply(function () {
                $scope.open_edit(row);
            });
        });

        GRID.on('del', function (row) {
            //
            API.del(row.id, function() {
                $scope.$apply(function () {
                    $scope.refresh()
                });
            }, function(e){alert(e);});
        });

        $scope.submit_edit = function(){
            //
            API.upd($scope.record_edit, function() {
                $scope.$apply(function () {
                    $scope.refresh();
                });
            },function(e){alert(e);});
        };

        $scope.refresh = function(){
            GRID.refresh();
            $scope.add_open = false;
            $scope.edit_open = false;

            $scope.record_add = {};
            $scope.record_edit = {};
        }

}];